<template>
  <el-dialog title="分配权限" :visible.sync="visiable" width="500px" :before-close="handleClose">
    <el-form ref="formData" label-width="80px"  v-loading="loading">
      <!--
              :data 绑定的渲染数据，数组
              show-checkbox 显示勾选框
              node-key 树节点的唯一标识属性名
              props 配置响应数据中对应展示的属性名 children 是子菜单的属性名，label显示的菜单名属性名
              :default-checked-keys 默认勾选的集合
              accordion 每次只能展开一个，会将之前展开把它隐藏
      -->
      <el-tree
        ref="tree"
        :data="perList"
        show-checkbox
        node-key="permissionId"
        accordion
        :default-checked-keys="menuIds"
        :props="{children: 'children', label: 'name'}">
      </el-tree>
      <el-form-item align="center" style="margin-top: 20px;">
        <el-button type="primary" @click="submitForm('formData')">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import permissionApi from '@/api/permission';
import roleApi from '@/api/role';
import {Key, PcCookie} from "@/utils/cookie";
export default {
  props:{
    visiable:{  // 弹出窗口
      type:Boolean,
      default:false
    },
    remoteClose: Function, // 用于关闭窗口
    roleId: {
      type:Number,
      default:null
    }
  },
  data(){
    return{
      perList: [],       // 存储所有的菜单
      loading: false,     // 加载中  true 显示加载中
      menuIds: [2],        // 角色所拥有的的菜单ids
    }
  },

  created() {
    this.fetchData();
  },

  watch:{
    roleId(val){
      if(val){
        this.getPermissionIdsByRoleId(val);
        this.fetchData();
      }
    }
  },

  methods: {
    // 根据角色ID查询该角色拥有的权限信息
    getPermissionIdsByRoleId(id) {
      roleApi.getPermissionIdsByRoleId(id).then(resp => {
        if (resp.code === 200) {
          this.menuIds = resp.data;
        }
      })
    },

    // 关闭窗口
    handleClose(){
      this.perList = [];
      this.menuIds = [];
      // 调用父组件的方法关闭窗口
      this.remoteClose();
    },

    fetchData() {
      permissionApi.getAllPermission().then(response => {
        if (response.code === 200) {
          this.perList = response.data;
        }
      })
    },

    // 提交
    submitForm(formName) {
      const checkedMenuIds = this.$refs.tree.getCheckedKeys();
      const data = {
        roleId: this.roleId,
        permissionIdList: checkedMenuIds
      }
      permissionApi.saveRolePermission(data).then(response => {
        if (response.code === 200) {
          // 权限分配成功 需要重新登录
          this.$confirm('权限分配成功后需要重新登录，是否重新登录？', '提示', { // 确认框
            type: 'info'
          }).then(() => {
            PcCookie.remove(Key.userInfoKey);
            PcCookie.remove(Key.accessTokenKey);
            PcCookie.remove(Key.refreshTokenKey);
            window.location.href = `http://localhost:9999`;
            //window.location.href = `http://admin.r2blog.cn`;
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '你选择不登录'
            })
            return false
          })
      } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有操作权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
        this.handleClose();
      })
    },
  }
}
</script>

<style scoped>

</style>
